
package com.campus.user;
import com.campus.common.ApiResponse;
import com.campus.security.JwtService;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController @RequestMapping("/api/auth") @Validated
public class AuthController {
  @Autowired private UserRepository repo;
  private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  @PostMapping("/register")
  public ResponseEntity<?> register(@RequestBody Map<String,String> body){
    String email = body.getOrDefault("email","");
    String studentId = body.getOrDefault("studentId","");
    String password = body.getOrDefault("password","");
    if(repo.existsByEmail(email) || repo.existsByStudentId(studentId)){
      return ResponseEntity.badRequest().body(ApiResponse.fail("email or studentId exists"));
    }
    User u = new User();
    u.setEmail(email); u.setStudentId(studentId);
    u.setPasswordHash(encoder.encode(password));
    repo.save(u);
    return ResponseEntity.ok(ApiResponse.ok(Map.of("id",u.getId())));
  }
  @PostMapping("/login")
  public ResponseEntity<?> login(@RequestBody LoginReq req){
    return repo.findByEmail(req.email())
      .filter(u-> new BCryptPasswordEncoder().matches(req.password(), u.getPasswordHash()))
      .<ResponseEntity<?>>map(u-> ResponseEntity.ok(ApiResponse.ok(Map.of("token", JwtService.generateToken(u.getEmail(), 86400000)))))
      .orElseGet(()-> ResponseEntity.status(401).body(ApiResponse.fail("invalid credentials")));
  }
  public record LoginReq(@NotBlank @Email String email, @NotBlank String password){}
}
